package com.wuzheng.wisgo.sanitation.cloud.resolver;

import com.wuzheng.wisgo.sanitation.cloud.repository.entity.person.User;
import com.wuzheng.wisgo.sanitation.cloud.service.person.UserService;
import com.wuzheng.wisgo.sanitation.framework.base.annotation.CurrentUser;
import com.wuzheng.wisgo.sanitation.framework.util.SpringContextUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author：hoipang
 * @date：Created in 2019-12-16
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<CurrentUser> loginUserClass = CurrentUser.class;
        if (methodParameter.hasParameterAnnotation(loginUserClass)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        UserService userService = (UserService) SpringContextUtils.getBeanByClass(UserService.class);

        String token = nativeWebRequest.getHeader("token");

        User user = userService.getToken(token);

        return user == null ? null : user;
    }
}
